const router = require('koa-router')()
const { SuccessModel } = require('../model/resModel')
const { delBlog, getList, newBlog, updataBlog, getDetail } = require('../controller/blog')
const loginCheck = require('../middleware/loginCheck')

router.prefix('/api/blog')

router.get('/list', async function (ctx, next) {
    const { author, keyword } = ctx.query
    const result = await getList(author, keyword)
    ctx.body = (new SuccessModel(result))
    await next()
});

router.post('/new', loginCheck, async function (ctx, next) {
    const blogData = ctx.request.body
    blogData.author = ctx.session.username
    const result = await newBlog(blogData)
    ctx.body = (new SuccessModel(result))

})

router.post('/update', loginCheck, async function (ctx, next) {
    const blogData = ctx.request.body
    blogData.author = req.session.username
    const result = await updataBlog(blogData)
    ctx.body = (new SuccessModel(result))
})

router.get('/detail', async function (ctx, next) {
    const { id } = ctx.query
    const result = await getDetail(id)
    ctx.body = (new SuccessModel(result))

})

router.post('/del', loginCheck, async function (req, res, next) {
    const { id } = req.body
    const author = req.session.username
    const result = await delBlog(id, author)
    if (result) {
        ctx.body = (new SuccessModel())
    }
    else {
        ctx.body = (new SuccessModel('删除失败'))
    }
})


module.exports = router
